import sys
import json
import urllib.parse
import urllib.request
from PySide6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLineEdit, QPushButton, QTableWidget, QTableWidgetItem, QHeaderView,
    QLabel, QMessageBox, QFrame # Added QFrame for visual separation
)
from PySide6.QtCore import Qt, QUrl
from PySide6.QtGui import QFont, QDesktopServices, QColor, QPalette


class QuarkDramaSearchApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("夸克短剧查询工具 🎬")
        self.setGeometry(300, 300, 1000, 750) # Slightly larger for more content

        # --- 深色模式配色方案 ---
        palette = self.palette()
        palette.setColor(QPalette.Window, QColor("#282c34"))
        palette.setColor(QPalette.WindowText, QColor("#ecf0f1"))
        palette.setColor(QPalette.Base, QColor("#3c4048"))
        palette.setColor(QPalette.Text, QColor("#ecf0f1"))
        palette.setColor(QPalette.Button, QColor("#61afef"))
        palette.setColor(QPalette.ButtonText, QColor("#282c34"))
        palette.setColor(QPalette.Highlight, QColor("#61afef"))
        palette.setColor(QPalette.HighlightedText, QColor("#282c34"))
        self.setPalette(palette)

        # 设置主窗口部件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        main_layout = QVBoxLayout(main_widget)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(15)

        # 设置字体
        font = QFont("Segoe UI", 10)
        self.setFont(font)

        # --- 搜索/操作区域 ---
        search_frame = QFrame()
        search_frame.setFrameShape(QFrame.StyledPanel)
        search_frame.setFrameShadow(QFrame.Raised)
        search_frame.setStyleSheet("""
            QFrame {
                background-color: #3c4048;
                border: 1px solid #4e535e;
                border-radius: 10px;
                padding: 15px;
            }
        """)
        search_layout = QHBoxLayout(search_frame)

        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入短剧名称进行搜索...")
        self.search_input.returnPressed.connect(self.search_dramas)
        self.search_input.setFixedHeight(40)
        self.search_input.setStyleSheet("""
            QLineEdit {
                padding: 10px;
                border: 1px solid #4e535e;
                border-radius: 8px;
                font-size: 14px;
                color: #ecf0f1;
                background-color: #282c34; /* Slightly darker input background */
            }
            QLineEdit:focus {
                border: 1px solid #61afef;
                background-color: #282c34;
            }
        """)
        search_layout.addWidget(self.search_input)

        self.search_btn = QPushButton("搜索")
        self.search_btn.clicked.connect(self.search_dramas)
        self.search_btn.setFixedHeight(40)
        self.search_btn.setStyleSheet("""
            QPushButton {
                background-color: #61afef;
                color: #282c34;
                border: none;
                border-radius: 8px;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #559edc;
            }
            QPushButton:pressed {
                background-color: #4a8bcc;
            }
        """)
        search_layout.addWidget(self.search_btn)

        self.list_all_btn = QPushButton("查看全部")
        self.list_all_btn.clicked.connect(self.list_all_dramas)
        self.list_all_btn.setFixedHeight(40)
        self.list_all_btn.setStyleSheet("""
            QPushButton {
                background-color: #28a745; /* Green for "All" button */
                color: white;
                border: none;
                border-radius: 8px;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #218838;
            }
            QPushButton:pressed {
                background-color: #1e7e34;
            }
        """)
        search_layout.addWidget(self.list_all_btn)

        self.today_update_btn = QPushButton("今日更新")
        self.today_update_btn.clicked.connect(self.today_update_dramas)
        self.today_update_btn.setFixedHeight(40)
        self.today_update_btn.setStyleSheet("""
            QPushButton {
                background-color: #ffc107; /* Orange for "Today" button */
                color: #282c34;
                border: none;
                border-radius: 8px;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #e0a800;
            }
            QPushButton:pressed {
                background-color: #c69500;
            }
        """)
        search_layout.addWidget(self.today_update_btn)

        main_layout.addWidget(search_frame)

        # --- 结果表格 ---
        self.result_table = QTableWidget()
        self.result_table.setColumnCount(3) # name, link, time
        self.result_table.setHorizontalHeaderLabels(["短剧名称", "短剧链接", "更新时间"])
        self.result_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) # Name stretches
        self.result_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch) # Link stretches
        self.result_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents) # Time fits content
        self.result_table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.result_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.result_table.doubleClicked.connect(self.open_link)

        # 表格样式：深色背景、亮色文字、蓝色高亮
        self.result_table.setStyleSheet("""
            QTableWidget {
                border: 1px solid #4e535e;
                border-radius: 8px;
                font-size: 13px;
                background-color: #3c4048;
                gridline-color: #4e535e;
                color: #ecf0f1;
                selection-background-color: #61afef;
                selection-color: #282c34;
            }
            QHeaderView::section {
                background-color: #4e535e;
                color: #ecf0f1;
                padding: 10px;
                border-bottom: 2px solid #61afef;
                font-weight: bold;
            }
            QTableWidget::item {
                padding: 6px;
            }
        """)
        main_layout.addWidget(self.result_table)

        # 状态标签
        self.status_label = QLabel("就绪")
        self.status_label.setAlignment(Qt.AlignCenter)
        self.status_label.setStyleSheet("color: #99aab5; font-size: 12px;")
        main_layout.addWidget(self.status_label)

    def fetch_data(self, endpoint, param_type=None, param_value=None):
        """通用数据获取函数，根据参数构建URL并请求API"""
        base_url = "https://www.duanju.click/api/short/quark"
        api_url = base_url

        if param_type == "text" and param_value:
            encoded_value = urllib.parse.quote(param_value)
            api_url = f"{base_url}?text={encoded_value}"
        elif param_type == "list":
            api_url = f"{base_url}?list"
        elif param_type == "today":
            api_url = f"{base_url}?today"

        self.status_label.setText("加载中... ⏳")
        QApplication.processEvents()

        try:
            with urllib.request.urlopen(api_url, timeout=10) as response: # Added timeout
                data = json.loads(response.read().decode('utf-8'))

                if data.get('code') != 200:
                    self.status_label.setText(f"API错误: {data.get('msg', '未知错误')} ❌")
                    self.result_table.setRowCount(0)
                    return False, None # Indicate failure

                return True, data.get('data', []) # Indicate success and return data

        except urllib.error.URLError as e:
            self.status_label.setText(f"网络请求错误: {e.reason} ❗")
            self.result_table.setRowCount(0)
            return False, None
        except json.JSONDecodeError:
            self.status_label.setText("数据解析错误: 服务器返回了无效数据 ❗")
            self.result_table.setRowCount(0)
            return False, None
        except Exception as e:
            self.status_label.setText(f"发生错误: {str(e)} ❗")
            self.result_table.setRowCount(0)
            return False, None

    def process_results(self, data):
        """将数据填充到表格中"""
        self.result_table.setRowCount(0) # Clear existing rows

        if not data:
            self.status_label.setText("没有找到相关结果 🤷‍♀️")
            return

        for row_data in data:
            row_idx = self.result_table.rowCount()
            self.result_table.insertRow(row_idx)

            # 短剧名称
            name = row_data.get('name', '未知名称')
            self.result_table.setItem(row_idx, 0, QTableWidgetItem(name))

            # 短剧链接
            link = row_data.get('link', '')
            if link and not link.startswith('http'):
                link = 'https://' + link # Ensure link has a scheme
            link_item = QTableWidgetItem(link)
            link_item.setToolTip(link) # Show full link on hover
            self.result_table.setItem(row_idx, 1, link_item)

            # 更新时间
            time = row_data.get('time', '未知时间')
            self.result_table.setItem(row_idx, 2, QTableWidgetItem(time))

        self.status_label.setText(f"找到 {self.result_table.rowCount()} 条结果 🎉")

    def search_dramas(self):
        """执行搜索操作"""
        keyword = self.search_input.text().strip()
        if not keyword:
            QMessageBox.warning(self, "输入错误", "请输入要搜索的短剧名称 🎬")
            return

        success, data = self.fetch_data("search", "text", keyword)
        if success:
            self.process_results(data)

    def list_all_dramas(self):
        """查看全部短剧"""
        success, data = self.fetch_data("list", "list")
        if success:
            self.process_results(data)

    def today_update_dramas(self):
        """查看今日更新短剧"""
        success, data = self.fetch_data("today", "today")
        if success:
            self.process_results(data)

    def open_link(self, index):
        """双击表格中的链接，使用系统浏览器打开"""
        if index.column() == 1: # 短剧链接在第二列 (索引为 1)
            url = self.result_table.item(index.row(), 1).text()
            if url:
                QDesktopServices.openUrl(QUrl(url))


if __name__ == "__main__":
    # 启用高清DPI缩放，确保界面在高分辨率屏幕上正常显示
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)

    app = QApplication(sys.argv)
    window = QuarkDramaSearchApp()
    window.show()
    sys.exit(app.exec())